from functools import wraps
from lambda_helper.authorization import extract_data_from_header
from lambda_helper.dynamo_models import UserInfo
from lambda_helper.s3_boto import is_running_on_aws_lambda
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not is_running_on_aws_lambda():
    handler = logging.StreamHandler()
    # format the log
    formatter = logging.Formatter('%(name)s - - [%(asctime)s] "%(message)s" %(levelname)%')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

class HttpRequest:

    def __init__(self, event, context):
        self.event = event
        self.context = context
        self.query = event.get('queryStringParameters', {})
        self.method = event.get('requestContext', {}).get('http', {}).get('method', 'GET')
        self.body = event.get('body', {})
        self.headers = event.get('headers', {})
        self.auth_token_data = extract_data_from_header(self.headers)
        self.user_info: UserInfo = None

    @staticmethod
    def Authorize(status_code=403, body="Forbidden"):
        def decorator(func):
            def wrapper(self: 'HttpRequest', *args, **kwargs):
                if self.auth_token_data is None:
                    logger.error(f"auth token is None, event: {self.event}")
                    return self.build_response(status_code=status_code, body=body)
                if not self.auth_token_data.is_valid():
                    logger.error(f"auth token is invalid, token data: {self.auth_token_data.__dict__}")
                    return self.build_response(status_code=status_code, body=body)
                self.user_info = self.auth_token_data.user_info
                return func(self, *args, **kwargs)
            return wrapper
        return decorator

    def get(self):
        '''
        没有实现，返回405
        '''
        return self.build_response(status_code=405, body="Method Not Allowed")
    
    def post(self):
        '''
        没有实现，返回405
        '''
        return self.build_response(status_code=405, body="Method Not Allowed")
    
    def put(self):
        '''
        没有实现，返回405
        '''
        return self.build_response(status_code=405, body="Method Not Allowed")
    
    def delete(self):
        '''
        没有实现，返回405
        '''
        return self.build_response(status_code=405, body="Method Not Allowed")
    
    def build_response(self, status_code=200, body=None, content_type="application/json"):
        return {
            'statusCode': status_code,
            'headers': {
                'Content-Type': content_type
            },
            'body': body
        }
    
    def handle(self):
        if self.method == 'GET':
            return self.get()
        elif self.method == 'POST':
            return self.post()
        elif self.method == 'PUT':
            return self.put()
        elif self.method == 'DELETE':
            return self.delete()
        else:
            return self.build_response(status_code=405, body="Method Not Allowed")